<template>
  <div id="menu">
    <el-button type="primary" @click="handleExport">导出地图</el-button>
  </div>
  <div id="map"></div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount } from 'vue'
import { Map, View } from 'ol'
import { Tile as TileLayer } from 'ol/layer'
import { XYZ } from 'ol/source'
import { MAPURL, ATTRIBUTIONS } from '../../constants'
import { exportMap } from './PrintMap'

let map: Map | null = null
const raster = new TileLayer({
  source: new XYZ({
    attributions: ATTRIBUTIONS,
    url: 'http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=3bc6874f2b919aa581635abab7759a3f',
    maxZoom: 20,
    // 需要配置跨域
    crossOrigin: 'anonymous'
  })
})

const initMap = () => {
  map = new Map({
    //初始化map
    target: 'map',
    //地图容器中加载的图层
    layers: [
      //加载瓦片图层数据
      raster
    ],
    view: new View({
      projection: 'EPSG:4326', // 坐标系，有EPSG:4326和EPSG:3 857
      center: [114.064839, 22.548857], // 深圳坐标
      //地图初始显示级别
      zoom: 12
    })
  })
}

const handleExport = () => {
  exportMap(map, '地图打印')
}

onMounted(() => {
  initMap()
})

onBeforeUnmount(() => {
  if (map) {
    map.dispose()
    map = null
  }
})
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#map {
  width: 100%;
  height: calc(100% - 50px);
}

#menu {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 50px;
}
</style>